﻿using Castle.MicroKernel.Facilities;
using Castle.MicroKernel.Registration;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;

using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using System.Reflection;


namespace LeoMVC.Web.Plumbing
{
    public class PersistenceFacility:AbstractFacility
    {
        protected override void Init()
        {
            var config = BuildDatabaseConfiguration();
            Kernel.Register(
                Component.For<ISessionFactory>()
                    .UsingFactoryMethod(_ => config.BuildSessionFactory()),
                Component.For<ISession>()
                    .UsingFactoryMethod(k => k.Resolve<ISessionFactory>().OpenSession())
                    .LifestylePerWebRequest()
                );
        }

        private Configuration BuildDatabaseConfiguration()
        {
            return Fluently.Configure()
                .Database(SetupDatabase)
                .Mappings(m => m.HbmMappings.AddFromAssembly(Assembly.Load("LeoMVC.Mapping")))
                .ExposeConfiguration(ConfigurePersistence)
                .BuildConfiguration();
        }


        protected virtual IPersistenceConfigurer SetupDatabase()
        {
            return
                MsSqlConfiguration.MsSql2008.ConnectionString(x => x.FromConnectionStringWithKey("ApplicationServices"))
                    .ShowSql();
        }


        protected virtual void ConfigurePersistence(Configuration config)
        {
            SchemaExport export=new SchemaExport(config);

        }
    }
}